package io.xxx.omni.oss.sdk

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.toJsonObject
import io.xxx.omni.oss.common.zoneOffset
import io.xxx.omni.oss.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import java.time.LocalDateTime
import java.util.*

@Component
class SnClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "http://api.open.beibei.com/outer_api/out_gateway/route.html"

    fun execute(store: Store, method: String, request: Map<String, Any>): JsonObject {
        val signMap = TreeMap(request)
        signMap["method"] = method
        signMap["timestamp"] = LocalDateTime.now().toEpochSecond(zoneOffset).toString()
        signMap["app_id"] = store.authorization["app_id"]
        signMap["session"] = store.authorization["session"]
        signMap["sign"] = sign(store.authorization["appSecret"], signMap)
        return restTemplate.postForEntity(httpUrl, signMap, String::class.java).body!!.toJsonObject()
    }

    private fun sign(appSecret: String, signMap: Map<String, Any>): String {
        val map = if (signMap is TreeMap) signMap else TreeMap(signMap)
        val builder = StringBuilder()
            .append(appSecret)
            .append(map.entries.joinToString("") { it.key + it.value })
            .append(appSecret)
        return DigestUtils.md5Hex(builder.toString()).uppercase()
    }
}